#!/bin/bash

# 应用名称
APP_NAME="soc-admin"
JAR_NAME="soc-admin.jar"
JAR_PATH="soc-admin/target/$JAR_NAME"

# 设置加密密钥环境变量
export JASYPT_ENCRYPTOR_PASSWORD=soc-web-2024

# 设置项目配置
export ACTIVE_PROFILE=dev
export JVM_OPTS="-Xms512m -Xmx1024m"
export DEBUG_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"

# 日志目录
LOG_DIR="logs"
LOG_PATH="$LOG_DIR/$APP_NAME.log"
GC_LOG_PATH="$LOG_DIR/gc.log"

# 创建日志目录
mkdir -p $LOG_DIR

# PID文件
PID_FILE="$APP_NAME.pid"

# 获取进程PID
get_pid() {
    if [ -f $PID_FILE ]; then
        echo $(cat $PID_FILE)
    fi
}

# 检查程序是否正在运行
is_running() {
    pid=$(get_pid)
    if [ -n "$pid" ]; then
        if ps -p $pid >/dev/null; then
            return 0
        fi
    fi
    return 1
}

# 启动应用
start() {
    if is_running; then
        echo "$APP_NAME is already running. pid=$(get_pid)"
        exit 1
    fi

    echo "Starting $APP_NAME ..."
    
    nohup java $JVM_OPTS $DEBUG_OPTS \
        -XX:+HeapDumpOnOutOfMemoryError \
        -XX:HeapDumpPath=$LOG_DIR \
        -XX:+PrintGCDetails \
        -XX:+PrintGCDateStamps \
        -Xloggc:$GC_LOG_PATH \
        -Dspring.profiles.active=$ACTIVE_PROFILE \
        -Djasypt.encryptor.password=$JASYPT_ENCRYPTOR_PASSWORD \
        -jar $JAR_PATH > $LOG_PATH 2>&1 &

    echo $! > $PID_FILE
    
    echo "Please check the log file: $LOG_PATH"
    sleep 1
    tail -f $LOG_PATH
}

# 停止应用
stop() {
    pid=$(get_pid)
    if [ -n "$pid" ]; then
        echo "Stopping $APP_NAME ..."
        kill $pid
        rm -f $PID_FILE
        
        # 等待进程结束
        for i in {1..30}; do
            if ! ps -p $pid >/dev/null; then
                echo "$APP_NAME stopped"
                return 0
            fi
            sleep 1
        done
        
        # 如果进程还在运行，强制结束
        echo "Force killing $APP_NAME ..."
        kill -9 $pid
        rm -f $PID_FILE
    else
        echo "$APP_NAME is not running"
    fi
}

# 重启应用
restart() {
    stop
    sleep 2
    start
}

# 查看状态
status() {
    if is_running; then
        echo "$APP_NAME is running. pid=$(get_pid)"
    else
        echo "$APP_NAME is not running"
    fi
}

# 查看日志
log() {
    if [ -f $LOG_PATH ]; then
        tail -f $LOG_PATH
    else
        echo "Log file not found: $LOG_PATH"
    fi
}

# 命令行参数处理
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    log)
        log
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|log}"
        exit 1
esac

exit 0